/**
 * 
 */
package edu.rit.cs.ws.servlets;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import edu.rit.cs.core.pojos.Symbol;
import edu.rit.cs.core.services.daos.SymbolDAO;

/**
 * A simple servlet to list the current symbols served by the webservice and
 * add new or update existing ones.
 * 
 * @author Abhishek Shrestha (axs1430)
 * @author Juan Saldana (jjs6109)
 * @author Victor Alvarez (vxa1557)
 */
public class SymbolServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  @Autowired
  private SymbolDAO sd;
  
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
  }

  @Override
  protected void doGet(final HttpServletRequest req,
    final HttpServletResponse resp) throws ServletException, IOException {

    moveOn(req, resp);
  }

  @Override
  protected void doPost(final HttpServletRequest req,
    final HttpServletResponse resp) throws ServletException, IOException {

    // No validation here
    Symbol symbol = new Symbol();
    symbol.setFullname(req.getParameter("fullname"));
    symbol.setPrice(Double.parseDouble(req.getParameter("price")));
    symbol.setId(req.getParameter("symbol"));
    sd.save(symbol);

    moveOn(req, resp);
  }

  /**
   * Common behavior after a POST or a GET.
   * 
   * @param req
   * @param resp
   * @throws ServletException
   * @throws IOException
   */
  protected void moveOn(final HttpServletRequest req,
    final HttpServletResponse resp) throws ServletException, IOException {

    req.getSession().setAttribute("symbols", sd.findAll());
    getServletContext().getRequestDispatcher("/Symbols.jsp").forward(req, resp);
  }
  
}
